package com.fc.commons.security;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class HMACUtil {
	/** 
	 * MAC算法可选以下多种算法 
     * <pre> 
     * HmacMD5  
     * HmacSHA1  
     * HmacSHA256  
     * HmacSHA384  
     * HmacSHA512 
     * </pre> 
     */ 
	private final static String KEY_MAC = "HmacSHA1"; 
	
	/** 
	 * 初始化HMAC密钥 
	 * @return 
	 * @throws Exception 
	 */  
	public static String initMacKey() throws Exception {  
	    KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);  
	  
	    SecretKey secretKey = keyGenerator.generateKey();
	    return Base64Util.encryptBASE64(secretKey.getEncoded());
	}
	
	/** 
	 * HMAC加密
	 *  
	 * @param data 
	 * @param key 
	 * @return 
	 * @throws Exception 
	 */  
	public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
	  
	    SecretKey secretKey = new SecretKeySpec(key.getBytes(), KEY_MAC);
	    Mac mac = Mac.getInstance(secretKey.getAlgorithm());  
	    mac.init(secretKey);
	  
	    return mac.doFinal(data);  
	  
	}
	
	/**
	 * HMAC加密
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptHMAC(String data,String key) throws Exception {
		byte[] temp = encryptHMAC(data.getBytes(), key);
		return SGlobalUtil.INSTANCE.bytes2String(temp);
	}
}
